import React, { Component } from 'react'
import { connect } from 'dva';
import MyNavBar from 'components/navbar';
import styles from './index.less'
import router from 'umi/router';
import { Button, Toast, Modal } from 'antd-mobile';
import common from '../../utils/common.less'
import { verificationMode, SERVICE_TYPE } from '../../utils/Enum'
import { pusherChannelTag, PROCESS_STATUS, AUTHENTICATION_FAIL_CODE } from 'utils/Enum'
/**
 * 短信验证
 * @author 马羽
 * @time 2020-4-13
 */

const alert = Modal.alert;
 
@connect(({ pdfModel, signatureModel, enterVerificationCodeModel }) => ({ pdfModel, signatureModel, enterVerificationCodeModel }))
class EnterVerificationCode extends Component {
    
    state = {
        val: '',
        countDown: 60,
        isFirst: true,  //是否是第一次获取验证码
        start: false,  //是否开始倒计时
        mask: false  //是否打开蒙版
    }

    timer = null  //定时器
    maxLen = 6  //验证码的最大长度
    hasShowModel = false  //是否展示过model

    //判断是不是个人
    get isPUSR() {
        const { userType } = this.props.pdfModel
        return userType === AUTHENTICATION_FAIL_CODE.PUSR
    }

    //获取用户电话
    get userPhone() {
        var { personalObj: { userData: { phone = '' } } } = this.props.pdfModel
        if(!phone) {
            const { enterpriseObj: { userData } } = this.props.pdfModel
            if(Object.keys(userData).length !== 0) {
                var { person: { phone = '' } } = userData
            }
        }
        return phone
    }

    //对电话进行隐藏
    get userPhoneEncryption() {
        const phone = this.userPhone
        let s = ''
        for(let i in phone) {
            if(i < 3 || i > phone.length - 3) {
                s += phone[i]
            } else {
                s += '*'
            }
        }
        return s
    }

    render() {
        const { val, countDown, isFirst, start, mask } = this.state
        return (
            <div className={styles.container}>
                <MyNavBar 
                    title={'请输入验证码'} 
                    backUrl={`/Signature`}
                />
                <header className={styles.headerTop}>
                    <div className={styles.header}>
                        本次操作需要短信确认，请输入{this.userPhoneEncryption}收到的短信验证码
                    </div>
                </header>
                <div className={styles.form}>
                    <input value={val} onChange={this.changeVCode} className={styles.input} placeholder="填写验证码"/>
                    <div onClick={this.startTimer} className={start ? styles.start : styles.end}>
                        {
                            start ?
                                `${countDown}后重新获取`
                                :
                                isFirst ?
                                '获取验证码'
                                :
                                '重新获取'
                        }
                    </div>
                </div>
                <div className={styles.footer}>
                    <Button
                        className={styles.btn}
                        type="primary"
                        disabled={val.length !== this.maxLen}
                        onClick={this.submit}
                    >提交</Button>
                    <div onClick={this.showMask} className={styles.info}>收不到验证码？</div>
                </div>
                {
                    mask ?
                        <div onClick={this.cancelMask} className={common.mask}></div>
                        :
                        null
                }
                <footer 
                    className={styles.maskFooter}
                    style={{
                        transform: `translateY(${mask ? 0 : 250}px)`
                    }}
                >
                    <div onClick={this.selectOther} className={styles.title}>选择其他验证方式</div>
                    <div className={styles.middle}></div>
                    <div onClick={this.cancelMask} className={styles.cancel}>取消</div>
                </footer>
            </div>
        )
    }

    changeVCode = e => {
        if(e.target.value.length === this.maxLen + 1) return
        this.setState({
            val: e.target.value
        })
    }


    startTimer = e => {
        //如果已经开始倒计时则直接返回
        if(this.state.start) return
        //发送验证码
        const { dispatch } = this.props
        const phone = this.userPhone
        dispatch({
            type: 'enterVerificationCodeModel/sendVCode',
            payload: {
                pusherChannelTag: pusherChannelTag,
                service: SERVICE_TYPE.CONFIRM_AUTH,
                phone: phone
            },
            callback: (state, msg) => {
                if(state === 'success') {
                    Toast.success('获取验证码成功')
                    //解决setInterval的延迟触发，先执行一次
                    this.setState(state => ({
                        countDown: state.countDown - 1,
                        isFirst: false,
                        start: true
                    }))
                    this.timer = setInterval(() => {
                        if(this.state.countDown > 1) {
                            this.setState(state => ({
                                countDown: state.countDown - 1,
                                isFirst: false,
                                start: true
                            }))
                        } else {
                            this.setState(state => ({
                                countDown: 60,
                                isFirst: false,
                                start: false
                            }))
                            clearInterval(this.timer)
                        }
                    }, 1000)
                } else {
                    Toast.fail(msg)
                }
            }
        })
    }


    showModel = (msg, fn = () => {}) => {
        alert('', msg, [{ 
            text: '确定', 
            onPress: fn, 
            style: 'default'
        }])
    }

    submit = async e => {
        /**
         * 签署流程
         * 先去获取保存在后台的表单数据
         * 在请求确认签署接口
         */
        const envelopeWsid = localStorage.getItem('envelopeWsid');
        const participantWsid = localStorage.getItem('participantWsid');
        const phone = this.userPhone
        const { val } = this.state
        const { dispatch } = this.props
        Toast.loading('签署中', 0)
        const getFormSearch = await dispatch({
            type: 'enterVerificationCodeModel/getFormSearch',
            payload: {
                envelopeWsid,
                participantWsid,
                query: {
                    fields: null,
                    filters: null,
                    sorts: null,
                    offset: 0,
                    limit: 1000
                }
            }
        })
        const { status, forms, message } = getFormSearch
        //如果获取表单数据成功
        if(status === 'success') {
            //请求确认签署接口
            const res = await dispatch({
                type: 'enterVerificationCodeModel/submit',
                payload: {
                    envelopeWsid,
                    participantWsid,
                    phone,
                    vCode: val,
                    query: {
                        signForms: forms.map(item => ({
                            formWsid: item.formWsid
                        }))
                    }
                }
            })
            const { status, msg } = res
            if(status === 'success') {
                router.push({
                    pathname: '/SignTheSuccess',
                    query: {
                        result: PROCESS_STATUS.UNKOWN_SIGN_SUCCESS
                    }
                })
            } else {
                this.showModel(msg)
            }
        } else {
            this.showModel(message)
        }
        Toast.hide()
    }

    //取消蒙版
    cancelMask = e => {
        this.setState({
            mask: false
        })
    }

    //显示蒙版
    showMask = e => {
        this.setState({
            mask: true
        })
    }

    //选择其他验证方式
    selectOther = e => {
        const { dispatch } = this.props
        dispatch({
            type: 'signatureModel/setMask',
            payload: {
                isShowSelect: true,
                verificationMode: verificationMode.ALIPAYVERIFICATION
            }
        })
        router.goBack()
    }

}

export default EnterVerificationCode